/**
 * 一键查询
 */
define([
    "dojo/_base/declare",
    "./js/DrawAction.js",
    "esri/geometry/Point",
    "esri/geometry/Polygon",
    "esri/Graphic",
    "esri/geometry/SpatialReference",
    "esri/tasks/support/FeatureSet",
    "esri/tasks/QueryTask",
    "esri/tasks/support/Query",
    "esri/geometry/geometryEngine",
  ], function (declare, DrawAction,Point,Polygon,Graphic,SpatialReference,
               FeatureSet,QueryTask,Query,geometryEngine) {

    return declare(null, {
        /**
         * 成员属性
         * @type {string}
         */
        mapView: Context.view,//地图视图
        layerId:"0",//当前分析图层id
        urls:{

        },
        /**
         * 获取素有通用的元素
         * (建议通过function的方式返回，防止因为缓存的原因导致元素事件无法激活)
         * @returns
         */
        elements:function(){//每次加载后均需要重新选择
            return{

            };
        },
        /**
         * 构造函数（初始化函数）
         */
        constructor: function () {
            this.init();
        },
        /**
         * 初始化函数
         */
        init:function () {
            this.initMenu();//需要在初始化完成后重新选择
            this.initUI();
            this.initUIEvent();
            this.initOpt();
        },
        initMenu:function () {
            this.mapView=Context.view;
        },
        initOpt:function () {
        },
        initUI:function(){

        },
        initUIEvent:function () {
            var that=this;

            $("#J_popoverInfo_close").on('click',function () {
                mui('#popover').popover('hide');
            })
            $("#J_query_point").on('click',function () {
                that.mapView.on('click',function (e) {
                    var mapPoint=e.mapPoint;
                    that.startQueryByGeometry(mapPoint);
                })
            })
            //空间查询
            $("#J_query_draw").on('click',function () {
                if(that.drawAction!=null){
                    that.drawAction.clearAllResult();
                }else{
                    that.drawAction=new DrawAction(that.mapView,{});
                }

                that.mapView.graphics.removeAll();
                that.drawAction.drawPolygon(function (polygon) {
                    that.curQueryGemo=polygon;
                    var graphic= that.drawAction.createGraphic(that.curQueryGemo);
                    that.anaGraphic=graphic.clone();
                    that.startQueryByGeometry(polygon);
                });
            })
            //属性查询
            $("#fuzzySearch").keyup(function(e){
                if (e.keyCode == 13) {
                    that.startQueryInfo();
                }
            });
            //定位
            $("#J_located").click(function () {
                that.goToCurLocation();
            });
        },
        /**
         * 通过浏览器提供的API获取位置
         *
         */
        goToCurLocation:function(){
            let that=this;
            if (navigator.geolocation){
                navigator.geolocation.getCurrentPosition(function (position) {
                    let lng = position.coords.longitude;
                    let lat = position.coords.latitude;
                    let prjService=new GeoProjectService();
                    // prjService.lngLatToXY(lng,lat,function (resGeoms) {
                        prjService.lngLatToXY(119.336402,26.120872,function (resGeoms) {
                        let point = {
                            type: "point",  // autocasts as new Point()
                            longitude: resGeoms[0].x,
                            latitude: resGeoms[0].y
                        };
                        let markerSymbol = {
                            type: "simple-marker",  // autocasts as new SimpleMarkerSymbol()
                            color: [226, 119, 40]
                        };
                        var pGraphic = new Graphic({
                            geometry: point,
                            symbol: markerSymbol
                        });
                        that.mapView.goTo({center:resGeoms[0],scale:11});
                    });
                });
            }else {
                alert("您的设备不支持定位功能");
            }
        },

        /**
         * 通过百度地图API实现定位
         * 百度定位http://www.5imoban.net/jiaocheng/jquery/201804033245.html
         * https://blog.csdn.net/qq_41756580/article/details/83378936
         */
        goToCurLocation2:function(){
            let that=this;
            let geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    // var mk = new BMap.Marker(r.point);
                    let lat = r.point.lat;
                    let lng = r.point.lng;
                    let gpsPoint = new BMap.Point(lng, lat);
                    let points=[gpsPoint];
                    let convertor = new BMap.Convertor();
                    convertor.translate(points, 1, 3, function(data){
                        alert(data);
                    });

                }
            });
        },
        /**
         * 通过单击列表显示要素消息窗口，同时漫游至位置(可以重载)
         * @param featureid 选中要素id
         */
        onListItemClick: function (gid) {
            var that = this;
            mui('#popover').popover('hide');
            if(that.queryResults!=null&&that.queryResults.length>0){
                for(var i=0;i<that.queryResults.length;i++){
                    var feature=that.queryResults[i];
                    if(feature.attributes["FID"]==gid){
                        var feature=that.queryResults[i];
                        that.showMoreInfo(feature,"项目名","业主,进展");
                        break;
                    }
                }
            }
        },
        startQueryByGeometry:function(geometry){
            var that=this;
            if(geometry==null)
                return;
            if(mapConfig==null||mapConfig.queryLayerConfig==null){
                mui.toast('请到mapConfig.js文件中配置查询图层');
                return;
            }
            var url=mapConfig.queryLayerConfig.layerUrl+"/"+mapConfig.queryLayerConfig.layerId;
            const queryTask = new QueryTask({
                url: url,
            });
            const titleField=mapConfig.queryLayerConfig.titleField;
            const  showfields=mapConfig.queryLayerConfig.showfields;
            const query = new Query();
            query.returnGeometry = true;
            query.outFields = ["*"];
            var geometry=geometry;
            if(geometry!=null)
                query.geometry = geometry;
            query.where="1=1";
            mui('#popover').popover('hide');
            queryTask.execute(query).then(function (results) {
                //绘制结果
                var obj={};
                obj.results=results;
                var resultFeatures=results.features;
                that.queryResults=resultFeatures;
                if(resultFeatures.length>1){
                    //绘制结果
                    let features=results.features;
                    that.drawResultData(features);
                    that.genResultList(features);
                }
                if(resultFeatures.length==1){
                    var feature=resultFeatures[0];
                    that.showMoreInfo(feature,titleField,showfields);
                }else {
                    mui.toast('没有查询结果');
                }
            }).catch(function () {
                mui.toast("查询结果出错，请检查服务！");
            });
        },

        /**
         * 要素，标题字段，显示字段
         * @param feature
         * @param titleField
         * @param showFields
         */
        showMoreInfo:function(feature,titleField,showFields){
            var that=this;
            var titleHtml=feature.attributes[titleField];
            $("#J_popoverInfo_title").html(titleHtml);
            var html='';
            showFields.split(",").forEach(function (value) {
                var field=
                    html+='<div class="mui-input-row poschoolName">';
                html+=' <label>'+value+':</label>';
                html+='<label style="width:60%;">'+feature.attributes[value]+'</label>';
                html+='</div>';
            });
            $("#J_popoverInfo_content").html(html);
            mui('#popover').popover('toggle');
            $(".mui-backdrop").remove();

            //高亮选中图层
            that.selectGraphic(feature);
        },
        /**
         * 信息查询
         * @param serverUrl
         * @param layerId
         * @param geometry
         */
        startQueryInfo: function (name,serverUrl,layerId,fidfield,queryfields,showfields) {
            const that = this;
            try{
                let kw=$("#fuzzySearch").val();
                let definitionExpression="项目名 like '%"+kw+"%'";
                const queryTask = new QueryTask({
                    url: that.urls.projectServiceUrl,
                });
                const query = new Query();
                query.returnGeometry = true;
                query.outFields = ["*"];
                let geometry=that.curQueryGemo;//用于空间属性查询
                if(geometry!=null)
                    query.geometry = geometry;
                query.where=definitionExpression;
                queryTask.execute(query).then(function (result) {
                    //绘制结果
                    let features=result.features;
                  that.genResultList(features);
                }).catch(function () {
                    layer.msg("查询结果出错，请检查服务！");
                    Context.index.hideLoading("J_queryModel");
                });
            }catch (e) {
                layer.msg("查询结果出错，请检查服务！");
                Context.index.hideLoading("J_queryModel");
            }
        },

        /**
         * 构建查询结果列表
         */
        genResultList:function(features){
            var that=this;
            let html='';
            for(feature of features) {
                let attributes = feature.attributes;
                let geometry = feature.geometry;
                let title = attributes[mapConfig.queryLayerConfig.titleField];
                html += '<li class="mui-table-view-cell" fid="'+attributes[mapConfig.queryLayerConfig.idField]+'">';
                html += '<a class="mui-navigate-right">';
                html += attributes[mapConfig.queryLayerConfig.titleField];
                html += ' </a>';
                html += ' </li>';
            }
            $("#J_query_result_list").html(html);
            $("#J_query_result_panel").css("display","block");
            $("#J_resource_canvas").css("display","none");
            app.offCanvasWrapper.offCanvas('show');
            //统一注册事件
            $("#J_query_result_list>li").each(function(i,o) {
                $(this).click(function () {
                    var gid= $(this).attr("fid");
                    if (typeof (that.onListItemClick) == "function") {
                        that.onListItemClick(gid);
                        app.offCanvasWrapper.offCanvas('close');
                    }
                });
            });
            // return html;
        },
        /**
         * 返回同步调用结果
         * @param result
         */
        drawResultData:function (resultFeatures) {
            var that=this;
            var graphics=[];
            for(var featureindex in resultFeatures){
                var symbol="";
                var feature=resultFeatures[featureindex];
                var geometry=feature.geometry;
                geometry.spatialReference=that.mapView.spatialReference;
                var geometryType=geometry.type.toLowerCase();
                if(geometryType=="point"){
                    symbol=graphicSymbolConfig.pointSymbol;
                }else  if(geometryType=="linestring"||geometryType=="polyline"){
                    symbol=graphicSymbolConfig.lineSymbol
                }else{
                    symbol=graphicSymbolConfig.polygonSymbol
                }
                var  inGraphic=new Graphic({
                    geometry:geometry,
                    attributes:feature.attributes,
                    symbol:symbol
                });
                graphics.push(inGraphic)
                that.mapView.graphics.add(inGraphic);
            }
        },

        /**
         * 计算面积
         */
        clacArea:function(g){
            return geometryEngine.planarArea(g, "square-meters").toFixed(1);
        },


        // 通过编辑的节点构建面
        createPolygon: function(vertices) {
            return new Polygon({
                rings: vertices,
                spatialReference:this.mapView.spatialReference
            });
        },
        createGraphic: function(polygon) {
            return new Graphic({
                geometry: polygon,
                symbol: {
                    type: "simple-fill",
                    color: [25, 25, 112, 0.8],
                    style: "solid",
                    outline: {
                        color: [25, 25, 112],
                        width: 2
                    }
                }
            });
        },

        /**
         * 高亮
         * @param feature
         */
        selectGraphic:function (selectGraphic) {
            var that=this;
            that.clearSelectGraphic();
            var symbol="";
            var scale="";
            var geometryType=selectGraphic.geometry.type.toLowerCase();
            if(geometryType=="point"){
                symbol=graphicSymbolConfig.pointSelectSymbol;
            }else  if(geometryType=="linestring"||geometryType=="polyline"){
                symbol=graphicSymbolConfig.lineSelectSymbol;
            }else{
                symbol=graphicSymbolConfig.polygonSelectSymbol;
            }
            that.curSelectGraphic=new Graphic({
                geometry:selectGraphic.geometry,
                symbol:symbol
            });
            that.mapView.graphics.add(that.curSelectGraphic);
            that.mapView.goTo({target:that.curSelectGraphic},{animate :false}).then(function () {
            });

        },
        /**
         * 清空选择
         */
        clearSelectGraphic:function () {
            if(this.curSelectGraphic){
                Context.view.graphics.remove(this.curSelectGraphic);
                $("#J_twoComplianceResultTb tr").removeClass('selected');
            }
        },

        /**
         * 清除结果
         */
        clearAllResult:function () {
            var that=this;
            if( that.mapView!=null)
                that.mapView.graphics.removeAll();
            that.curQueryGemo=null;
            that.curQueryGraphic=null;
            $("#J_oneButtonQuery_result").css("visibility","hidden");
            $("#J_oneButtonQuery_result").css("display","none");
        },
        /**
         * 判断服务是否可用
         */
        validateAgsServer:function (serverDatas) {
            let errorMsg="";
            for(const serverData of serverDatas){
                $.ajax({
                    type: "GET",
                    async: false,
                    url: serverData.url,
                    error:function () {
                        errorMsg+="<div>图层："+serverData.name+"，服务无效。</div>"
                    }
                });
            }
            return errorMsg;
        }
    });
});


